package com.yonyou.cloud.member.adapters.openapi.configurer;

import com.yonyou.cloud.member.adapters.dto.ApiResponseDto;
import com.yonyou.cloud.member.exceptions.ApplicationRuntimeException;
import com.yonyou.cloud.member.exceptions.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class OpenApiWebMvcConfigurer implements WebMvcConfigurer {
    Logger logger = LoggerFactory.getLogger(OpenApiWebMvcConfigurer.class);

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new HandlerExceptionResolver() {
            @Override
            public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
                ApiResponseDto<?> responseDto = new ApiResponseDto<>(false);
                ModelAndView mav = new ModelAndView();
                if (e instanceof BusinessException) {
                    mav.setStatus(HttpStatus.OK);
                    responseDto.setMessage(e.getMessage());
                } else if (e instanceof ApplicationRuntimeException) {
                    mav.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
                    responseDto.setMessage(e.getMessage());
                    // logger.error("", e);
                } else {
                    mav.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
                    responseDto.setMessage("服务器内部错误，请刷新后重试或联系管理员");
                    // logger.error("", e);
                }
//                Map<String, Object> resultMap = new HashMap<>();
//                resultMap.put("responseData", responseDto);

                MappingJackson2JsonView view = new MappingJackson2JsonView();
                // view.setAttributesMap(resultMap);
                view.addStaticAttribute("responseData", responseDto);
                view.setExtractValueFromSingleKeyModel(true);
                // view.setModelKey("responseData");
                mav.setView(view);
                return mav;
            }
        });
    }
}
